// index.js
Page({
  data:{
    isShowCamera: 'true',
    windowHeight:'',
    windowWidth: '',
    isShowImage: '',
    imageHeight: '',
    imageWidth: '',
    imageUrl: '',
    x: '',
    y: '',
    width:'',
    height: '',
    imageUrl1:'',
  },
  onLoad(options){
    this.ctx = wx.createCameraContext();
    this.app = getApp();
    let {windowWidth, windowHeight} = wx.getSystemInfoSync();
    this.setData({
      windowHeight,
      windowWidth,
      imageWidth: windowWidth,
      imageHeight: windowHeight,
      x: 0,
      y: 0,
      width: 100,
      height: 100,
    });
    this.DrawImage(this.app.globalData.imageUrl);
  },
  
  DrawImage:function(imageUrl){
    console.log(imageUrl, 'DrawImage');
    wx.getImageInfo({
      src: imageUrl,
      success: res =>{
        this.canvas = wx.createCanvasContext('mycanvas', this);
        let width = this.data.windowWidth;
        let height = width /  res.width * res.height;
        this.setData({
          imageHeight: height,
          imageWidth: width,
        })
        // 绘画图片
        this.canvas.drawImage(imageUrl, 0, 0 , width, height);
        // 这里绘画必须要用setTimeout不然会找不到canvas
        this.canvas.draw(true, 
          setTimeout(()=>{
            this.createImage("mycanvas", 0, 0,
            this.data.imageWidth,
            this.data.imageHeight)
          },1000)
          );
        console.log("alterImage is ok");
      }
    })
  },

  alterImage(){
    this.setData({
      isShowImage: false,
    })
    wx.canvasToTempFilePath({
     canvasId: 'mycanvas',
     x: this.data.x,
     y: this.data.y,
     width: this.data.width,
     height: this.data.height,
     destHeight: this.data.height,
     destWidth: this.data.width,
     success: resp =>{
       let imageUrl1 = resp.tempFilePath;
       console.log(imageUrl1);
       this.setData({
        imageUrl1,
       });
       this.setData({
         isShowImage: true,
       })
     }
    }, this)
  },

  nowChange: function(res){
    let x = res.detail.x;
    let y = res.detail.y;
    this.setData({
      x,
      y,
    })
  },

  nowScale: function(res){
    let data = res.detail;
    this.setData({
      x: data.x,
      y: data.y,
      height: 100 * data.scale,
      width: 100 * data.scale,
    });
  },

  createImage(canvasId, sx, sy, width, height){
    console.log(canvasId);
    wx.canvasToTempFilePath({
      // 必须要用canvasId
      canvasId: 'mycanvas',
      x: sx,
      y: sy,
      width: width,
      height: height,
      destWidth: width,
      destHeight: height,
      success: resp=>{
       const app = getApp();
       app.globalData.imageUrl = resp.tempFilePath;
       console.log(resp);
       this.setData({
         isShowImage: true,
         imageUrl: app.globalData.imageUrl,
       });
       console.log("draw success");
      },
      fail: resp=>{
        console.log(resp);
      }
    }, this);
  }

})
